import 'dart:convert';
import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:ecy_app_flutter/constant/constant.dart';
import 'package:ecy_app_flutter/model/SysFile.dart';
import 'package:ecy_app_flutter/routes/group/model/EcyImages.dart';
import 'package:ecy_app_flutter/routes/group/model/ValleyCirclePost.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';

import '../../../EcyRouter.dart';
import '../../../ecycommon/EcyCommonWidgets.dart';
import '../../../ecycommon/EcyRequestBaseManager.dart';
import '../../../model/EcyApiCommonResponse.dart';
import '../model/ValleyCircleAddModel.dart';

class EcyGroupPublishPage extends EcyCommonBaseWidget {
  late int? id;
  EcyGroupPublishPage({required super.key, required this.id});

  late _EcyGroupPublishPageState state;

  @override
  State<EcyCommonBaseWidget> createState() {
    state = _EcyGroupPublishPageState(id);
    return state;
  }
}

class _EcyGroupPublishPageState extends EcyCommonBaseWidgetState {
  late EcyCommonBaseWidget controller;
  late int? id;
  _EcyGroupPublishPageState(this.id);

  final ScrollController _scrollController = ScrollController();
  final _formKey = GlobalKey<FormState>();
  final _titleController = TextEditingController();
  final _subTitleController = TextEditingController();

  final ImagePicker _picker = ImagePicker();
  int currentIndex = 0;

  final ValleyCircleAddModel _valleyCircleAddModel = ValleyCircleAddModel();
  final List<EcyImages> _ecyImageList = [];
  List<XFile> _xFileList = [];
  final int _maxFileCount = 6;

  bool _loading = false;
  bool _publishFlag = false;

  @override
  void initState() {
    super.initState();

    if (id != null) {
      loadDetail(id!);
    }
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
    _titleController.dispose();
    _subTitleController.dispose();
  }

  Future<void> loadDetail(int id) async {
    Map<String, dynamic> body = {
      "id": id,
    };
    var response = await EcyRequestbasemanager()
        .post("/app/api/app/valley/circle/detail", body);
    if (response != null) {
      var commonResponse =
          EcyApiCommonResponse.fromJson(response, (response) => json);
      if (commonResponse.code == 0 || commonResponse.code == 200) {
        ValleyCirclePost valleyCirclePost =
            ValleyCirclePost.fromJson(response["data"]);
        _valleyCircleAddModel.id = valleyCirclePost.id;
        setState(() {
          _titleController.text = valleyCirclePost.title ?? "";
          _subTitleController.text = valleyCirclePost.content ?? "";
          _ecyImageList
              .addAll(valleyCirclePost.valleyCirclePostImageList ?? []);
          _publishFlag = valleyCirclePost.status == "1";
        });
      }
    }
  }

  Future<void> _pickMultiImage() async {
    final List<XFile> pickedFiles = await _picker.pickMultiImage(
        limit: _maxFileCount, imageQuality: 100); // 从相册选择图片
    // final pickedFile = await _picker.pickImage(source: ImageSource.camera); // 从相机选择图片
    if (pickedFiles != null && pickedFiles.isNotEmpty) {
      _xFileList.addAll(pickedFiles);
      var sublist =
          _xFileList.length > 6 ? _xFileList.sublist(0, 6) : _xFileList;
      setState(() {
        _xFileList = sublist;
      });
    }
  }

  /// 0|草稿 1|发布
  Future<void> saveValleyCirclePost({int type = 0}) async {
    if (_loading) {
      return;
    }
    _loading = true;
    if (_ecyImageList.isEmpty && _xFileList.isEmpty) {
      EasyLoading.showToast("请上传图片", duration: const Duration(seconds: 1));
      return;
    }
    if (_titleController.text == null || _titleController.text.trim().isEmpty) {
      EasyLoading.showToast("请添加标题", duration: const Duration(seconds: 1));
      return;
    }
    if (_subTitleController.text == null ||
        _subTitleController.text.trim().isEmpty) {
      EasyLoading.showToast("请写点什么和大家分享", duration: const Duration(seconds: 1));
      return;
    }

    EasyLoading.show(status: '处理中...');
    try {
      for (var xFile in _xFileList) {
        var multipartFile =
            MultipartFile.fromFileSync(xFile.path, filename: xFile.name);
        var formData = FormData.fromMap({
          "file": multipartFile,
        });
        var response =
            await EcyRequestbasemanager().post("/file/upload", formData);
        if (response != null) {
          var commonResponse =
              EcyApiCommonResponse.fromJson(response, (response) => json);
          if (commonResponse.code == 0 || commonResponse.code == 200) {
            var sysFile = SysFile.fromJson(response["data"]);
            EcyImages ecyImages = EcyImages()..originalUrl = sysFile.name;
            _ecyImageList.add(ecyImages);
          }
        }
      }

      for (var ecyImage in _ecyImageList) {
        ecyImage.originalUrl =
            ecyImage.originalUrl?.replaceFirst(Constant.OSS_FILE_PATE_PREFIX, "").replaceFirst(Constant.FILE_PATE_PREFIX, "");
      }

      Map<String, dynamic> body = {};
      body["id"] = _valleyCircleAddModel.id;
      body["title"] = _titleController.text;
      body["content"] = _subTitleController.text;
      body["images"] = _ecyImageList;
      String url = type == 0 ? "/valley/circle/add" : "/valley/circle/publish";
      var response =
          await EcyRequestbasemanager().post("/app/api/app$url", body);
      if (response != null) {
        var commonResponse =
            EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          EasyLoading.showToast((type == 0 || _publishFlag) ? "保存成功" : "发布成功",
              duration: const Duration(seconds: 1));
        }
      }

      if (type == 0) {
        if (id == null) {
          EcyRouter.pushReplacementNoParams(
              context, EcyRouter.myGroupDraftListPage);
        } else {
          Navigator.pop(context, true);
        }
      } else {
        Navigator.pop(context, true);
      }
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 1));
    } finally {
      EasyLoading.dismiss();
      _loading = false;
    }
  }

  void _removeImage(int index, {int type = 0}) {
    if (type == 0) {
      setState(() {
        _ecyImageList.removeAt(index);
      });
    } else {
      setState(() {
        _xFileList.removeAt(index);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> widgetList = [
      Expanded(
        flex: 5,
        child: Container(
          height: 40.0,
          padding: const EdgeInsets.only(left: 10),
          child: TextButton(
              onPressed: () {
                saveValleyCirclePost(type: 1);
              },
              style: const ButtonStyle(
                alignment: Alignment.center,
                backgroundColor: WidgetStatePropertyAll(Color(0xFFEA4B9B)),
                foregroundColor: WidgetStatePropertyAll(Colors.white),
              ),
              child: Text(
                _publishFlag ? '保存' : '发布',
                style: const TextStyle(
                  height: 1,
                  fontSize: 18,
                  leadingDistribution:
                      TextLeadingDistribution.even, // 设置leading策略
                ),
              )),
        ),
      )
    ];
    if (!_publishFlag) {
      widgetList.insert(
          0,
          Expanded(
              flex: 1,
              child: GestureDetector(
                onTap: saveValleyCirclePost,
                child: Column(
                  children: [
                    const Padding(padding: EdgeInsets.only(bottom: 4)),
                    const Image(
                        image: AssetImage('assets/images/ic_drafts.png'),
                        width: 32),
                    Text(
                      id != null ? "保存" : "存草稿",
                      style: const TextStyle(
                        fontSize: 12,
                        color: Color(0xFF8C8C8C),
                        fontFamily: "PingFang SC",
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ],
                ),
              )));
    }

    return Scaffold(
      backgroundColor: Colors.white,
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
          leadingWidth: 50.w,
          leading: GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              EcyRouter.pop(context, "");
            },
            child: Align(
              alignment: Alignment.centerRight,
              child: Image.asset(
                "assets/images/ic_back.png",
                width: 30.w,
              ),
            ),
          ),
          titleSpacing: 0,
          backgroundColor: Colors.white,
          centerTitle: true,
          title: Text(
            "发布",
            style: TextStyle(
                fontFamily: "PingFang SC",
                fontSize: 16.sp,
                color: const Color(0xD9000000),
                fontWeight: FontWeight.w600),
          )),
      body: SingleChildScrollView(
        child: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            //触摸收起键盘
            FocusScope.of(context).requestFocus(FocusNode());
          },
          child: Container(
            color: Colors.white,
            padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 18),
            child: Form(
              key: _formKey,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.max,
                children: [
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 8),
                    child: SizedBox(
                      height: 60,
                      child: _loadImages(),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(left: 8, top: 13),
                    child: TextFormField(
                        controller: _titleController,
                        decoration: const InputDecoration(
                          hintText: '添加标题',
                          hintFadeDuration: Duration.zero,
                          border: InputBorder.none,
                          counterText: '',
                          hintStyle: TextStyle(
                            color: Color(0xFFBFBFBF),
                            fontFamily: "PingFang SC",
                            fontWeight: FontWeight.w700,
                            fontSize: 16,
                          ),
                        ),
                        maxLength: 30,
                        minLines: 1,
                        maxLines: 2,
                        onTapOutside: (event) {
                          FocusScope.of(context).focusedChild?.unfocus();
                        }),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(left: 8, top: 2),
                    child: TextFormField(
                        controller: _subTitleController,
                        decoration: const InputDecoration(
                          hintText: '写点什么和大家分享...',
                          hintFadeDuration: Duration.zero,
                          border: InputBorder.none,
                          hintStyle: TextStyle(
                            color: Color(0xFFBFBFBF),
                            fontFamily: "PingFang SC",
                            fontWeight: FontWeight.w500,
                            fontSize: 14,
                          ),
                          counterText: '',
                        ),
                        minLines: 1,
                        maxLines: 12,
                        maxLength: 500,
                        onTapOutside: (event) {
                          FocusScope.of(context).focusedChild?.unfocus();
                        }),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
      bottomNavigationBar: BottomAppBar(
        color: Colors.white,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: widgetList,
        ),
      ),
    );
  }

  Widget _loadImages() {
    Widget avatar = Image.asset('assets/images/login_app_icon.png',
        width: 60, height: 60, fit: BoxFit.fitHeight);
    int ecyImageLength = _ecyImageList.length;
    int xFileLength = _xFileList.length;
    int sum = ecyImageLength + xFileLength;
    return ListView.builder(
      shrinkWrap: true,
      physics: const AlwaysScrollableScrollPhysics(),
      scrollDirection: Axis.horizontal, // 设置滚动方向为水平
      itemCount: sum + 1,
      itemBuilder: (context, index) {
        if (_ecyImageList.isNotEmpty && index < ecyImageLength) {
          var ecyImage = _ecyImageList[index];
          return Padding(
            padding: const EdgeInsets.only(right: 8),
            child: Stack(
              children: [
                CachedNetworkImage(
                  width: 60.w,
                  height: 60.w,
                  imageUrl: ecyImage.originalUrl ?? "",
                  imageBuilder: (context, imageProvider) => Container(
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(8.r)),
                        image: DecorationImage(
                            image: imageProvider, fit: BoxFit.cover)),
                  ),
                  placeholder: (context, url) => avatar,
                  errorWidget: (context, url, error) => avatar,
                ),
                Positioned(
                  top: 0.0,
                  right: 0.0,
                  width: 20,
                  height: 20,
                  child: GestureDetector(
                    child: SizedBox(
                      child: Image.asset('assets/images/ic_delete_1.png'),
                    ),
                    onTap: () => _removeImage(index),
                  ),
                ),
              ],
            ),
          );
        }
        if (_xFileList.isNotEmpty &&
            ecyImageLength - 1 < index &&
            index < sum) {
          var xFile = _xFileList[index - ecyImageLength];
          return Padding(
              padding: const EdgeInsets.only(right: 8),
              child: Stack(
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(4),
                    child: SizedBox(
                        width: 60,
                        height: 60,
                        child: Image.file(
                          File(xFile.path),
                          width: 60,
                          height: 60,
                          fit: BoxFit.cover,
                        )),
                  ),
                  Positioned(
                    top: 0.0,
                    right: 0.0,
                    width: 20,
                    height: 20,
                    child: GestureDetector(
                      child: SizedBox(
                        child: Image.asset('assets/images/ic_delete_1.png'),
                      ),
                      onTap: () =>
                          _removeImage(index - ecyImageLength, type: 1),
                    ),
                  ),
                ],
              ));
        }
        if (sum < 6) {
          return SizedBox(
            height: 60,
            width: 60,
            child: GestureDetector(
              onTap: () {
                _pickMultiImage();
              },
              child: const Image(
                  image: AssetImage('assets/images/ic_add.png'), width: 60),
            ),
          );
        }
      },
    );
  }
}
